<template>
	<view :class="config.style">
		<FullscreenLoading :loading="loading" :config="config"></FullscreenLoading>
		<!-- #ifdef H5-->
		<Top :config="config"></Top>
		<!-- #endif -->
		<view class="main-section top">
			<view class="material-info">
				<view class="material-icon">
					<image mode="widthFix" :src="data.material_icon" class="image"></image>
				</view>
				<view class="material-title">
					{{data.title}}
				</view>
			</view>
			
			<view class="download-btn-sec">
				<button type="default" class="submit" hover-class="hover" @click="downloadStart">立即下载</button>
			</view>
		</view>
		
		<view class="weixin-tip" :class="weixinTipShow?'show':'hidden'">
			<image mode="widthFix" :src="weixinTipPic" class="image"></image>
		</view>
	</view>
</template>

<script>
	import { mapState,mapMutations } from 'vuex'
	import Top from '../common/top.vue'
	
	export default {
		components: {
			Top,
		},
		data() {
			return {
				loading: true, //加载中
				weixinTipPic: '',
				weixinTipShow: false,
				urlParams: {},
				userInfo : {}, //用户数据
				data: {},
			}
		},
		onLoad(option) { //option为object类型，会序列化上个页面传递的参数
		    //console.log(option); //打印出上个页面传递的参数。
			this.urlParams = option
			
			Promise.all([this.getData()]).then(res => {
				//加载完成
				this.loading = false
			})
		},
		created() {
			//获取已登录用户数据
			this.getUserInfo()
			// #ifdef H5
			//设置远程微信提示url地址
			let siteroot = window.location.protocol+"//"+window.location.host
			this.weixinTipPic = siteroot + '/addons/muu_classroom_plugin_material/resource/images/weixin_tip.png'
			// #endif
		},
		computed: {
			...mapState(['config'])
		},
		methods: {

			/**
			 * 获取资料详情数据
			 */
			getData: function(){
				let that = this
				return new Promise((resolve, reject) => {
					let params = this.urlParams
					let data = {}
						
					//获取数据
					let url = '';
						//#ifdef H5
						url = 'entry/site/material'
						data.m = 'muu_classroom_plugin_material'
						data.action = 'download'
						data.sign = params.sign
						//#endif
						//#ifdef MP-WEIXIN
						url = 'entry/wxapp/material'
						data.m = 'muu_classroom'
						data.action = 'detail'
						data.id = params.id
						//#endif
					this.util.request({
						url : url,
						data : data,
						success: function (res) {
							if (res.data.code == 200) {
								console.log(res.data)
								that.data = res.data.data
							}
							if (res.data.code == 0) {
								uni.showModal({
								    title: '提示',
								    content: res.data.msg,
									showCancel: false,
								    success: function (res) {
								        if (res.confirm) {
								            console.log('用户点击确定');
											uni.navigateBack({
											    delta: 1
											});
								        }
								    }
								});
							}
							resolve(res.data)
						}
					})
				})
			},
			
			/**
			 * 获取已登录用户数据
			 */
			getUserInfo: function(){
				let that = this
				let userInfo = uni.getStorageSync('userInfo') || {}
				this.userInfo = userInfo
			},
			
			/**
			 * 开始下载
			 */
			downloadStart() {
				let that = this
				// #ifdef H5
				let ua = window.navigator.userAgent.toLowerCase()
				if (ua.match(/MicroMessenger/i) == 'micromessenger') {
					// 弹出提示框
					this.weixinTipShow = true
				}else{
					// 开始下载
					let material_url = that.data.download_url + '&sign=' + that.urlParams.sign
					//console.log(material_url)
					window.location.href = material_url;
				}
				// #endif
				
				// #ifdef MP
				//下载资料
				uni.showLoading({
				    title: '下载中，请稍后'
				});
				let url = 'entry/wxapp/material'
				let data = {
					'm': 'muu_classroom',
					'sign' : that.urlParams.sign,
					'action' : 'download'
				}
				//console.log(data)
				//获取数据
				this.util.request({
					url : url,
					data : data,
					success: function (res) {
						if (res.data.code == 200) {
							//console.log(res.data)
							let downloadTask = uni.downloadFile({
							    url: res.data.data.material_url, //仅为示例，并非真实的资源
								
							    success: (res) => {
							        if (res.statusCode === 200) {
										//console.log(res)
										console.log(`${wx.env.USER_DATA_PATH}` + "/" + that.data.filename)
										uni.getFileSystemManager().saveFile({
											tempFilePath: res.tempFilePath,
											filePath: `${wx.env.USER_DATA_PATH}` + "/" + that.data.filename,
										})
										
										uni.showModal({
											title: '是否打开文件',
											content: '',
											success(ans) {
												if (ans.confirm) {
													uni.openDocument({
														filePath: `${wx.env.USER_DATA_PATH}` + "/" + that.data.filename,
														showMenu: true,
														success: function (ress) {
															console.log('打开文档成功');
														},
													})
												}
											}
										})
							        }
							    }
							});
							
							downloadTask.onProgressUpdate((res) => {
							    console.log('下载进度' + res.progress);
							    console.log('已经下载的数据长度' + res.totalBytesWritten);
								if(res.progress == 100){
									uni.hideLoading();
								}
							    //console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
							
							    // 测试条件，取消下载任务。
							    if (res.progress > 50) {
							        //downloadTask.abort();
							    }
							});
						}
						if (res.data.code == 0) {
							uni.showModal({
							    title: '提示',
							    content: res.data.msg,
								showCancel: false,
							    success: function (res) {
							        if (res.confirm) {
							            console.log('用户点击确定');
										uni.navigateBack({
										    delta: 1
										});
							        }
							    }
							});
						}
					}
				})
				// #endif
			}
		},

		/**
		 * 监听用户点击右上角转发到朋友圈
		 */
		onShareTimeline() {
			
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f8f8f8;
	}
	
	.material-info {
		
		.material-icon {
			width: 140rpx;
			height: 140rpx;
			margin: 100rpx auto 40rpx auto;
			image {
				width: 140rpx;
				height: 140rpx;
			}
		}
		.material-title {
			font-size: 32rpx;
			font-weight: 800rpx;
			text-align: center;
		}
	}
	
	.download-btn-sec {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 20rpx;
		text-align: center;
		padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		z-index: 10;
		.submit {
			display: block;
			color: #fff;
			border-radius: 90rpx;
			&::after {
				border: 0;
			}
		}
	}
	
	.Blue {
		.download-btn-sec {
			button {
				background-color: $Blue;
			}
		}
	}
	.Green {
		.download-btn-sec {
			button {
				background-color: $Green;
			}
		}
	}
	.LightRed {
		.download-btn-sec {
			button {
				background-color: $LightRed;
			}
		}
	}
	.Orange {
		.download-btn-sec {
			button {
				background-color: $Orange;
			}
		}
	}
	.LightPink {
		.download-btn-sec {
			button {
				background-color: $LightPink;
			}
		}
	}
	.Magenta {
		.download-btn-sec {
			button {
				background-color: $Magenta;
			}
		}
	}

	.weixin-tip {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: rgba(0,0,0,.6);
		z-index: 120;
		text-align: center;
	}
</style>
